package com.mlan.userap.okhttp;

import android.util.Log;

import com.google.gson.Gson;
import com.mlan.userap.AppConfig;
import com.mlan.userap.untils.LogHelper;

import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class OkHttpHelper {


    public static String TAG = "OkHttpService";

    private static final OkHttpClient client = new OkHttpClient();
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private static String Tag = "OkHttpHelper";

    private OkHttpHelper() {
        // 私有构造方法，防止实例化
    }

    /**
     * 发送 GET 请求
     *
     * @param url      请求地址
     * @param callback 泛型回调函数
     * @param <T>      返回的实体类型
     */
    public static <T> void getData(String url, JsonCallBackData<T> callback) {
        String geturl = url;
        if (!url.startsWith("http")) geturl = AppConfig.apiUrl + url;
        Request request = new Request.Builder()
                .url(geturl)
                .get()
                .addHeader("token", AppConfig.token)
                .build();
        Log.w(Tag, geturl + "," + AppConfig.token);
        client.newCall(request).enqueue(callback);
    }

    public static <T> void get(String url, JsonCallBack<T> callback) {
        String geturl = url;
        if (!url.startsWith("http")) geturl = AppConfig.apiUrl + url;
        Request request = new Request.Builder()
                .url(geturl)
                .get()
                .addHeader("token", AppConfig.token)
                .build();
        Log.w(Tag, geturl + "," + AppConfig.token);
        client.newCall(request).enqueue(callback);
    }

    /**
     * 发送 GET 请求
     *
     * @param url      请求地址
     * @param params   键值对参数
     * @param callback 泛型回调函数
     * @param <T>      返回的实体类型
     */
    public static <T> void get(String url, Map<String, String> params, JsonCallBack<T> callback) {

        String geturl = url;
        if (!url.startsWith("http")) geturl = AppConfig.apiUrl + url;
        Log.d(TAG, "地址：" + geturl);
        HttpUrl.Builder urlBuilder = HttpUrl.parse(geturl).newBuilder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
            }
            Log.d(TAG, "参数：" + params);
        }
        String finalUrl = urlBuilder.build().toString();

        Request request = new Request.Builder()
                .url(finalUrl)
                .get()
                .addHeader("token", AppConfig.token)
                .build();
        Log.w(Tag, finalUrl);
        request.headers().toString();
        Log.d(TAG, "请求头：" + request.headers().toString());
        client.newCall(request).enqueue(new JsonCallBack<T>() {
            @Override
            public void onSuccess(ApiResponse<T> result,String value2) {
                Log.d(TAG, "请求结果：" + value2);
                callback.onSuccess(result,value2);
            }

            @Override
            public void onError(Exception error) {
                Log.d(TAG, "请求异常：" + error.getMessage());
                callback.onError(error);
            }
        });
    }

    /**
     * 发送 POST 请求
     *
     * @param url      请求地址
     * @param data     请求数据（JSON 格式）
     * @param callback 泛型回调函数
     * @param <T>      返回的实体类型
     */
    public static <T> void post(String url, Object data, JsonCallBack<T> callback) {
        String posturl = url;
        if (!url.startsWith("http")) posturl = AppConfig.apiUrl + url;

        Gson gson = new Gson();
        String json = gson.toJson(data);
        RequestBody requestBody = RequestBody.create(JSON, json);

        Request request = new Request.Builder()
                .url(posturl)
                .post(requestBody)
                .addHeader("token", AppConfig.token)
                .build();
        LogHelper.i(url + "=>" + json);
        client.newCall(request).enqueue(callback);
    }

    public static <T> void postData(String url, Object data, JsonCallBackData<T> callback) {
        String posturl = url;
        if (!url.startsWith("http")) posturl = AppConfig.apiUrl + url;

        Gson gson = new Gson();
        String json = gson.toJson(data);
        RequestBody requestBody = RequestBody.create(JSON, json);

        Request request = new Request.Builder()
                .url(posturl)
                .post(requestBody)
                .addHeader("token", AppConfig.token)
                .build();
        LogHelper.i(url + "=>" + json);
        client.newCall(request).enqueue(callback);
    }

    public static <T> void uploadVoiceFile(String url, String voicePath, long time, JsonCallBackData<T> callback) {
        String posturl = url;
        if (!url.startsWith("http")) posturl = AppConfig.apiUrl + url;

        OkHttpClient upClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS) // 连接超时30秒
                .writeTimeout(60, TimeUnit.SECONDS)   // 写入超时60秒（上传文件可能需要更长时间）
                .readTimeout(60, TimeUnit.SECONDS)    // 读取超时30秒
                .build();

        File voiceFile = new File(voicePath);
        // 创建 MultipartBody 用于上传文件和参数
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                // 添加文件参数
                .addFormDataPart("file", voiceFile.getName(),
                        RequestBody.create(MediaType.parse("audio/*"), voiceFile))
                // 添加 time 参数
                .addFormDataPart("time", time + "")
                .build();

        // 创建 Request
        Request request = new Request.Builder()
                .url(posturl)
                .post(requestBody)
                .addHeader("token", AppConfig.token)
                .build();

        // 异步执行请求
        upClient.newCall(request).enqueue(callback);
    }
}